//TreeSetTest4.java
package com.ylaihui.setitf;

import java.util.Comparator;
import java.util.Objects;
import java.util.TreeSet;

class User{
    int id;
    String name;

    public User() {
    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}
public class TreeSetTest4 {
    public static void main(String[] args) {

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.id,u2.id);
                }
                else
                    throw new RuntimeException("无法比较的数据类型");

            }
        };

        TreeSet set = new TreeSet(comparator);
        set.add(new User(111,"Andy"));
        set.add(new User(111,"Jimmy"));
        set.add(new User(333,"Caddy"));
        set.add(new User(444,"lisimmy"));
        set.add(new User(555,"ylaihui"));
        set.add(new User(555,"hahaha"));

        for (Object obj : set) {
            System.out.println(obj);
        }
    }
}
/*
User{id=111, name='Andy'}
User{id=333, name='Caddy'}
User{id=444, name='lisimmy'}
User{id=555, name='ylaihui'}
 */
